package cn.jbolt.ndemo;

import cn.hutool.core.util.StrUtil;

import cn.jbolt.ai.app.service.AiAppMessageService;
import cn.jbolt.ai.app.service.AiAppService;
import cn.jbolt.ai.app.service.AiAppSessionService;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.config.AppConfigConstant;
import cn.jbolt.ai.core.chain.config.LlmConfig;
import cn.jbolt.ai.core.chain.node.provider.EventNodeProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.jboltai.capability.model.JBoltAI;
import com.jboltai.event.EventErrorType;
import com.jboltai.event.ai.aichat.AIChatEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class InfoAnalyseNode implements EventNodeProvider {
    @Autowired
    private AiAppService aiAppService;
    @Autowired
    private AiAppSessionService aiAppSessionService;
    @Autowired
    private AiAppMessageService aiAppMessageService;
    private static final Logger logger = LoggerFactory.getLogger(InfoAnalyseNode.class);

    public AIChatEvent provide(JsonNode nodeConfig, ChainContext context) {
        AIChatEvent event = JBoltAI.chat();
        try {
            //根据配置初始化event
            configEvent(nodeConfig, context, event);
            event.onSuccess((e, res) -> {
                //配置项要求，把结果输出到上下文，交给下一个节点，继续处理
                context.setAttr("ai_result", res.getContent());
                try {
                    context.sendResponseMsg(res.getContent(), "json");
                } catch (Exception e1) {
                    e.fail(EventErrorType.PROGRAM_EXCEPTION,e1 );
                    context.sendErrorMsg("程序异常，请重试...");
                }
            });
            event.onFail((e, error) -> {
                context.sendErrorMsg(error.getMsg());
            });

            return event;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ChatNodeHandler process 异常,异常原因", e);
            context.sendErrorMsg( "网络异常,请稍后重试....");
        }
        return null;
    }

    private LlmConfig configEvent(JsonNode nodeConfig, ChainContext context, AIChatEvent event) {
        Long sessionId = context.getAiSession().getId();

        LlmConfig config = LlmConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_LLM));
        String prompt = generatePrompt(config, context);
        event.prompt(prompt).imgs(context.getSocketData().getData().get("file").asText());
        event.setStream(false);
        if (config.getModelType() != null) {
            event.setModel(config.getModelType());
        }
        if (StrUtil.isNotBlank(config.getDefaultModel())) {
            event.setModelName(config.getDefaultModel());
        }
        if (config.getMaxTokens() > 0) {
            event.setMaxTokens(config.getMaxTokens());
        }
        if (StrUtil.isNotBlank(config.getSystemRole())) {
            event.systemMessage(config.getSystemRole());
        }
        if (config.getTemperature() != null&& config.getTemperature()>0) {
            event.setTemperature(config.getTemperature());
        }
        if (config.getTopP() != null&& config.getTopP()>0) {
            event.setTopP(config.getTopP());
        }
        if (config.getTopK() != null&& config.getTopK()>0) {
            event.setTopK(config.getTopK());
        }
        return config;

    }

    /**
     * 生成提示词
     *
     * @param config  配置
     * @param context 上下文
     * @return 处理后的提示词
     */
    private String generatePrompt(LlmConfig config, ChainContext context) {
        if (StrUtil.isBlank(config.getPromptTpl())) {
            return context.getSocketData().getDataAsChatData().getContent().getText();
        }

        String template = config.getPromptTpl();
        if (context.getArgs() == null || context.getArgs().isEmpty()) {
            return template;
        }

        for (String key : context.getArgs().keySet()) {
            Object value = context.getArgs().get(key);
            if (value != null) {
                // 处理可能存在的空格情况，如 ${ key } 或 ${key}
                template = template.replaceAll("\\$\\{\\s*" + key + "\\s*\\}", value.toString());
            }
        }

        return template;
    }

}
